﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using StyleMVVM.DependencyInjection.Impl;

namespace StyleMVVM.DependencyInjection
{
	public class ImportConnectionStringAttribute : Attribute, IImportAttribute
	{
		public ImportConnectionStringAttribute()
		{
			Required = true;
		}

		public string Name { get; set; }

		public bool Required { get; set; }

		public IImportAttributeInfo ProvideImportInfo(object memberInfo)
		{
			string connectionString = Name;

			if (string.IsNullOrEmpty(connectionString))
			{
				PropertyInfo propertyInfo = memberInfo as PropertyInfo;

				if (propertyInfo != null)
				{
					connectionString = propertyInfo.Name;
				}
				else
				{
					ParameterInfo parameterInfo = memberInfo as ParameterInfo;

					if (parameterInfo != null)
					{
						connectionString = parameterInfo.Name;
					}
				}
			}

			return new ImportAttributeInfo
				       {
					       ImportName = "",
					       Required = Required,
					       Volatile = false,
					       ExportActivator =
						       new FuncExportActivator((x, y, z) => ConfigurationManager.ConnectionStrings[connectionString], true)
				       };
		}
	}
}